#define _CRT_SECURE_NO_WARNINGS 1

#include"SL.h"

ListNode* BuySpace(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	assert(newnode);
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

bool Empty(ListNode* pHead)
{
	assert(pHead);
	return pHead->next == pHead;
}

ListNode* ListCreate()
{
	ListNode* phead = (ListNode*)malloc(sizeof(ListNode));
	assert(phead);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(pHead);
}	

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	printf("guard <=> ");
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		printf("%d <=> ",cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* newnode = BuySpace(x);
	ListNode* curprev = pHead->prev;
	newnode->next = pHead;
	pHead->prev = newnode;
	curprev->next = newnode;
	newnode->prev = curprev;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(!Empty(pHead));
	ListNode* prev = pHead->prev->prev;
	ListNode* delete = pHead->prev;
	prev->next = pHead;
	pHead->prev = prev;
	free(delete);
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* newnode = BuySpace(x);
	ListNode* next = pHead->next;
	pHead->next = newnode;
	newnode->prev = pHead;
	newnode->next = next;
	next->prev = newnode;
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(!Empty(pHead));

	ListNode* next = pHead->next;
	ListNode* nnext = next->next;
	pHead->next = nnext;
	nnext->prev = pHead;
	free(next);

}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* cur = pHead->next;
	while (cur != pHead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = BuySpace(x);
	ListNode* curprev = pos->prev;
	newnode->next = pos;
	pos->prev = newnode;
	curprev->next = newnode;
	newnode->prev = curprev;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	assert(!Empty(pos));

	ListNode* posnext = pos->next;
	ListNode* posprev = pos->prev;
	posnext->prev = posprev;
	posprev->next = posnext;
	free(pos);
}


